import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
    //求前k个最大元素
    public static int[] fun(int k,int[]arr){
        int[]ret=new int[k];
        if(arr==null||k<=0)return ret;
        PriorityQueue<Integer>priorityQueue=new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            //小根堆
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });

        for (int tmp=0;tmp < arr.length; tmp++) {
            //建小根堆 k个元素
            if(priorityQueue.size()<k){//size的大小也会增加
                priorityQueue.offer(arr[tmp]);
            }else {
                //如果大于栈顶就将栈顶出栈，新元素入栈
                if (arr[tmp] > priorityQueue.peek()) {
                    priorityQueue.poll();
                    priorityQueue.offer(arr[tmp]);
                }
            }
        }
        for (int i = 0; i < k; i++) {
            ret[i]=priorityQueue.poll();
        }
        return ret;
    }
    public static void main(String[] args) {

        int[]arr=new int[]{27,15,19,18,28,34,65,49,25,37};
        System.out.println(Arrays.toString(fun(5, arr)));

    }
    public static void main1(String[] args) {
        PriorityQueue<Integer>priorityQueue=new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            //大根堆
            public int compare(Integer o1, Integer o2) {
                return o2-o1;
            }
        });
        int[]arr=new int[]{27,15,19,18,28,34,65,49,25,37};

        for (int i = 0; i < arr.length; i++) {
            priorityQueue.offer(arr[i]);
        }
        //前5个最大的元素
        for (int i = 0; i < 5; i++) {
            System.out.print(priorityQueue.poll()+" ");
        }

    }
}
